﻿using System;
using System.Collections.Generic;
using System.Text;
using RabbitMQ.Client.Events;
using RabbitMQDemo.Common;

namespace RabbitMQDemo.Consumer
{
    public class Priority
    {
        private const string ExchangeName = "priority_exchange";

        private const string QueueName = "priority_queue";

        private const string RoutingKey = "priority_routing";

        public static void Receive(string[] args)
        {
            using var connection = MQClient.GetConnection();
            using var channel = connection.CreateModel();

            // 声明交换机
            channel.ExchangeDeclare(exchange: ExchangeName, type: "direct", durable: false, autoDelete: false, arguments: null);

            // 声明队列
            channel.QueueDeclare(queue: QueueName, durable: false, exclusive: false, autoDelete: false, arguments: new Dictionary<string, object> {
                { "x-max-priority", 10 } // 最大优先级，必须设置，否则消息优先级不生效
            });
            channel.QueueBind(queue: QueueName, exchange: ExchangeName, routingKey: RoutingKey, arguments: null);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var message = Encoding.UTF8.GetString(ea.Body.ToArray());
                Console.WriteLine($"[Priority][{ea.BasicProperties.Priority}]received：{message}");
            };

            channel.BasicConsume(queue: QueueName, autoAck: true, consumerTag: "testConsumer", noLocal: false, exclusive: false, arguments: null, consumer: consumer);

            Console.WriteLine("按任意键退出");
            Console.ReadKey();
        }
    }
}
